package com.dly.blog.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.dly.blog.content.RedisContent;
import com.dly.blog.dto.email.EmailSendDTO;
import com.dly.blog.exception.AuthExceptionEnum;
import com.dly.blog.provider.email.EmailServiceProvider;
import com.dly.blog.service.EmailCaptchaService;
import com.dly.blog.utile.RedisUtils;
import jodd.util.RandomString;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author: DaiLiYu
 * @Date: 2023/7/19 17:54
 */
@Service
@AllArgsConstructor
public class EmailCaptchaServiceImpl implements EmailCaptchaService {

    private final RedisUtils redisUtils;

    private final EmailServiceProvider emailServiceProvider;

    private static final String captchaTemplate = "你的验证码是：{}";

    @Override
    public void send(String email) {
        String exit = redisUtils.getCacheObject(RedisContent.CAPTCHA_EMAIL + email);
        if(ObjectUtil.isNotNull(exit)){
            throw AuthExceptionEnum.EMAIL_CAPTCHA_IS_SEND.getAuthException();
        }
        String code = RandomUtil.randomNumbers(6);
        redisUtils.setCacheObject(RedisContent.CAPTCHA_EMAIL + email, code, 2, TimeUnit.MINUTES);
        String format = StrUtil.format(captchaTemplate, code);

        EmailSendDTO emailSendDTO = new EmailSendDTO();
        emailSendDTO.setEmailToList(List.of(email));
        emailSendDTO.setSubject("验证码");
        emailSendDTO.setMailText(format);

        emailServiceProvider.sendEmail(emailSendDTO);
    }
}
